// 观察者模式：观察者列表可以直接定义在Subject内部，被观察者直接触发观察者的监听

// 观察者列表
function ObserverList () {
  this.list = []
  this.add = observer => this.list.push(observer)
  this.get = i => this.list[i]
  this.getSize = () => this.list.length
  this.indexOf = (observer, start) => this.list.indexOf(observer, start)
  this.removeAt = i => this.list.splice(i, 1)
}

// 观察者
function Observer (update) {
  this.update = update
}

// 目标
function Subject () {
  this.observers = new ObserverList()
  this.addObserver = observer => this.observers.add(observer)
  this.removeObserver = observer => this.observers.removeAt(this.observers.indexOf(observer))
  this.notify = data => {
    let len = this.observers.getSize()
    for (let i = 0; i < len; i++) {
      this.observers.get(i).update(data)
    }
  }
}

export { Observer, Subject }
